package groep3.ssc.skaterViews;

import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.TextView;

public class SkaterTextView extends TextView
{

    private static final float TEXT_SIZE_STEPS = 10;
    private static final double SCALE_SIZE_X = 0.9;
    private static final double SCALE_SIZE_Y = 0.8;

    public SkaterTextView(Context context)
    {
        super(context);
        initialise();
    }

    public SkaterTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        initialise();
    }

    private void initialise()
    {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());
        setIncludeFontPadding(false);
        setGravity(Gravity.CENTER);
        setPadding(0, 0, 0, 0);
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textBoxWidth, int textBoxHeight)
    {
        if (textBoxWidth <= 0 || textBoxHeight <= 0 || text.length() <= 0)
            return;

        int maxWidth = (int) (textBoxWidth * SCALE_SIZE_X);
        int maxHeight = (int) (textBoxHeight * SCALE_SIZE_Y);

        mTestPaint.set(this.getPaint());
        mTestPaint.setTextSize(0);

        System.out.println("Height" + maxHeight);
        Rect bounds = new Rect();

        while (bounds.width() < maxWidth && bounds.height() < maxHeight)
        {
            mTestPaint.getTextBounds(text, 0, text.length(), bounds);
            mTestPaint.setTextSize(mTestPaint.getTextSize() + TEXT_SIZE_STEPS);
        }

        mTestPaint.setTextSize(mTestPaint.getTextSize() - TEXT_SIZE_STEPS);
        mTestPaint.getTextBounds(text, 0, text.length(), bounds);

        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTestPaint.getTextSize());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int parentHeigth = MeasureSpec.getSize(heightMeasureSpec);
        refitText(this.getText().toString(), parentWidth, parentHeigth);
        this.setMeasuredDimension(parentWidth, parentHeigth);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after)
    {
        refitText(text.toString(), this.getWidth(), this.getHeight());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        if (w != oldw)
        {
            refitText(this.getText().toString(), w, h);
        }
    }

    //Attributes
    private Paint mTestPaint;
}
